import { Button, Card, Form, Icon, Input, Modal, Radio, Steps, Tooltip, message } from "antd";
import React from "react";
import styles from "./index.less"
import { memDeptAccessSetting, memDeptAccessValidate } from "@/services/aigcUser";

class ConfigurationPage extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      current:0,
      typeList:{
        0:{
          value:0,
          title:"企业微信",
          settingName:"企业微信同步通讯录配置",
          tips:`<div id="u14_text" class="text ">
                <p><span>该过程是获取当前企业微信的通讯录信息，这一步骤需要企业微信的主管理员执行相应的授权操作，并提供必要的配置参数。</span></p><br><p><span>需企业提供信息：</span></p><p><span>企业id、应用Agentid、应用Seccret。</span></p><br><p><span>参考文档：</span></p><p><span>https://open.dingtalk.com/document/orgapp/contacts-overview</span></p>
              </div>`
        },
        2:{
          value:2,
          title:"企业钉钉",
          settingName:"企业钉钉同步通讯录配置",
          tips:`<div id="u18_text" class="text ">
                <p><span>该过程是获取当前企业钉钉的通讯录信息，这一步骤需要企业钉钉的主管理员执行相应的授权操作，并提供必要的配置参数。</span></p><br><p><span>需企业提供信息：</span></p><p><span>corpld 、API Token、Agentld、APPKey、AppSecret。</span></p><br><p><span>参考文档：</span></p><p><span>https://open.dingtalk.com/document/orgapp/contacts-overview</span></p>
              </div>`
        },
        3:{
          value:3,
          title:"对接企业系统",
          settingName:"企业系统同步通讯录",
          tips:`<div id="u22_text" class="text ">
                <span>与企业HR系统对接，同步通讯录，需双方技术协作，无默认配置项。
              </div>`
        }
      },
      type:-1,
      visible:false
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  changeType = e => {
    this.setState({
      type:e.target.value
    })
  }

  toNext = () => {
    const { type } = this.state
    const { settingInfo } = this.props;
    if(type == -1){
      message.error("请选择对接渠道/类型")
    }else{
      this.setState({
        current:1
      },() => {
        if(settingInfo && settingInfo.settingJson && (type == 0 || type == 2)){
          this.props.form.setFieldsValue(settingInfo.settingJson)
        }
      })
    }
  }

  doComplete = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        this.doOk(values)
      }
    })
  }

  doOk = async values => {
    console.log(values);
    const {  type } = this.state;
    let setting = type == 3 ? '' : JSON.stringify(values)
    const res = await memDeptAccessSetting({type,setting})
    message.info(res.message)
    if(res.code == -1){}else{
      this.props.changePart("setting-complete")
    }
  }

  toBack = () => {
    this.setState({
      current:0
    })
  }

  onCancel = () => {
    this.setState({
      visible:false
    })
  }

  onOk = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        this.toValidateUser(values)
      }
    })
  }

  toValidateUser = async values => {
    const { settingInfo } = this.props;
    const res = await memDeptAccessValidate(values)
    if(res.data){
      this.setState({
        visible:false,
        current:0,
        type:settingInfo ? settingInfo.type : -1
      })
    }else{
      message.error("管理员账号错误")
    }
    
  }

  changeCurrent = current => {
    this.setState({
      current
    })
  }

  render(){
    const { current,typeList,type,visible } = this.state;
    const { form:{getFieldDecorator} } = this.props;
    const radioStyle = {
      display: 'block',
      height: '30px',
      lineHeight: '30px',
    };
    const formItemLayout = {
			labelCol: { span: 5 },
			wrapperCol: { span: 19 },
		};
		const formTailLayout = {
			labelCol: { span: 0 },
			wrapperCol: { span: 19, offset: 5 },
		};
    const renderToolTip = (tips,radioValue) => (
      <Tooltip title={<div dangerouslySetInnerHTML={{__html:tips}}></div>} placement="right" overlayStyle={{maxWidth:600}}>
        <Icon type="question-circle" style={{marginLeft:8,fontSize:16,color:radioValue == type ? '#1A1A1A' : '#8F9297'}}  />
      </Tooltip>
    )
    const renderFieldsLable = (fieldName,tip) => (
      <span>
        {fieldName}&nbsp;
        <Tooltip title={tip}><Icon type='question-circle-o' /></Tooltip>
      </span>
    )
    const renderWarningCard = (showBtn) => (
      <div className={showBtn ? `${styles.warningBox} ` : `${styles.warningBox} ${styles.warningBoxModal}`}>
        <img src="../../../newUI/warning.png" style={{width:20,marginRight:8}} />
        <div>
          <div className={styles.warningTitle}>谨慎操作</div>
          <div className={styles.warningContent}>
            不可轻易修改对接方式，更换对接方式需要系统管理员操作；<br></br>
            更换对接方式后需要重新对接才可生效。
          </div>
          {
            showBtn ?  <div className={styles.linkBtn} onClick={() => this.setState({visible:true})}>更换对接方式</div> : ''
          }
          
        </div>
      </div>
    )
    return (
      <Card className={styles.configPage} bordered={false}>
        <Steps size="small" current={current} style={{marginBottom:32}}>
          <Steps.Step title='选择对接渠道/类型' />
          <Steps.Step title='填写配置信息' />
          <Steps.Step title='完成配置' />
        </Steps>

        {
          //选择对接渠道/类型
          current == 0 ? (
            <Card className={styles.contentBox} bordered={false}>
              <div className={styles.contentTitle}>对接渠道/类型</div>
              <div className={styles.content}>
                <Radio.Group value={type} onChange={this.changeType}>
                  {
                    Object.values(typeList).map((item,index) => {
                      return <Radio key={item.value} value={item.value} style={radioStyle}>{item.title}{renderToolTip(item.tips,item.value)}</Radio>
                    })
                  }
                </Radio.Group>

                <div>
                  <Button type="primary" style={{margin:'24px 0 0 24px'}} onClick={this.toNext}>下一步</Button>
                </div>
              </div>
              
            </Card>
          ) : ''
        }
        {
          //填写配置
          current == 1 ? (
            <Card className={styles.contentBox} bordered={false}>
              <div className={styles.contentTitle}>{typeList[type].settingName}</div>
              <div className={styles.content}>
                <Form {...formItemLayout} style={{width:600}}>
                  {
                    //企业微信
                    type == 0 ? (
                      <div>
                        <Form.Item label={renderFieldsLable('企业Id','登录企业微信管理后台，在"我的企业>企业信息"中找到企业ID')}>
                          {getFieldDecorator("corpId", {
                            rules: [
                              { required: true, message: "请填写企业Id" },
                            ],
                          })(
                            <Input placeholder={"请输入企业Id"} style={{ width: "94%" }} />
                          )}
                        </Form.Item>
                        <Form.Item label={renderFieldsLable("应用AgentId",'企业微信管理后台"应用管理"中自建应用部分，点击"创建应用"，创建完成后即可获得AgentId和Secret')}>
                          {getFieldDecorator("agentId", {
                            rules: [
                              { required: true, message: "请填写应用AgentId" },
                            ],
                          })(
                            <Input placeholder={"请输入应用AgentId"} style={{ width: "94%" }} />
                          )}
                        </Form.Item>
                        <Form.Item label={renderFieldsLable('应用Secret','企业微信管理后台"应用管理"中自建应用部分，点击"创建应用"，创建完成后即可获得AgentId和Secret')}>
                          {getFieldDecorator("agentSecret")(
                            <Input placeholder={"请输入应用Secret"} style={{ width: "94%" }} />
                          )}
                        </Form.Item>
                      </div>
                    ) : ''
                  }
                  {
                    //钉钉
                    type == 2 ? (
                      <div>
                        <Form.Item label={renderFieldsLable('corpId','登录钉钉管理后台，在"我的企业>企业信息"中找到企业ID')}>
                          {getFieldDecorator("corpId")(
                            <Input placeholder={"请输入corpId"} style={{ width: "94%" }} />
                          )}
                        </Form.Item>
                        <Form.Item label={renderFieldsLable('API Token','登录钉钉管理后台，在"我的企业>企业信息"中找到API Token')}>
                          {getFieldDecorator("apiToken")(
                            <Input placeholder={"请输入API Token"} style={{ width: "94%" }} />
                          )}
                        </Form.Item>
                        <Form.Item label={renderFieldsLable('AgentId','钉钉管理后台"应用管理"中自建应用部分，点击"创建应用"，创建完成后即可获得AgentId、AppKey和AppSecret')}>
                          {getFieldDecorator("agentId")(
                            <Input placeholder={"请输入AgentId"} style={{ width: "94%" }} />
                          )}
                        </Form.Item>
                        <Form.Item label={renderFieldsLable('APPKey','钉钉管理后台"应用管理"中自建应用部分，点击"创建应用"，创建完成后即可获得AgentId、AppKey和AppSecret')}>
                          {getFieldDecorator("appKey")(
                            <Input placeholder={"请输入APPKey"} style={{ width: "94%" }} />
                          )}
                        </Form.Item>
                        <Form.Item label={renderFieldsLable('AppSecret','钉钉管理后台"应用管理"中自建应用部分，点击"创建应用"，创建完成后即可获得AgentId、AppKey和AppSecret')}>
                          {getFieldDecorator("appSecret")(
                            <Input placeholder={"请输入AppSecret"} style={{ width: "94%" }} />
                          )}
                        </Form.Item>
                      </div>
                    ) : ''
                  }
                  {
                    //系统
                    type == 3 ? (
                      <div className={styles.typeStyle3}>
                        <div>与企业HR系统对接，同步通讯录，需双方技术协作，无默认配置项。</div>
                        <div>点击完成后会新增企业对接应用通讯录的菜单权限。</div>
                        <div>请联系开发人员对接。</div>
                      </div>
                    ) : ''
                  }
                </Form>
                
                <div style={{padding:'24px 0 0 0',paddingLeft:type != 3 ? 125 : 0}}>
                  <Button type="primary" onClick={this.doComplete}>完成</Button>
                  <Button type="primary" style={{background: '#E7E7E7',color:"#000000",border:"#E7E7E7",marginLeft:8}} onClick={this.toBack}>返回上一步</Button>
                </div>
              </div>
            </Card>
          ) : ''
        }
        {
          current == 2 ? (
            <Card className={styles.contentBox} bordered={false}>
              <div className={styles.contentTitle}>同步通讯录已设置完毕</div>
              <div className={styles.content}>
                {renderWarningCard(true)}
                <div>
                  <Button type="primary" style={{margin:'24px 0 0 24px'}} onClick={() => this.props.changePart("setting-complete")}>返回组织</Button>
                </div>
              </div>
            </Card>
          ) : ''
        }
        
        {
          visible ? (
            <Modal
              title='更换通讯录对接方式'
              visible={visible}
              onCancel={this.onCancel}
              onOk={this.onOk}
              destroyOnClose
            >
              {renderWarningCard(false)}
              <Form {...formItemLayout}>
                <Form.Item label="管理员账号">
                  {
                    getFieldDecorator("userName",{rules:[{required:visible,message:"请输入管理员账号"}]})(
                      <Input />
                    )
                  }
                </Form.Item>
                <Form.Item label="管理员密码">
                  {
                    getFieldDecorator("password",{rules:[{required:visible,message:"请输入管理员密码"}]})(
                      <Input.Password />
                    )
                  }
                </Form.Item>
              </Form>
            </Modal>
          ) : ''
        }
        
      </Card>
    )
  }
}


export default Form.create()(ConfigurationPage)